/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.task.impl  
 */
package com.apache.task.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.apache.database.constant.Validator;
import com.apache.task.entity.TaskEntity;

/**
 * description:  配置文件读取工具类
 * @author Hou Dayu 创建时间：2015-1-14  
 * @Copyright(c)2014:
 */
public class XmlReader {

	private String filePath;
	private static XmlReader instance;
	private String fileName = "taskconfig.xml";

	private XmlReader() {
		filePath = TaskUtil.getClassLoaderPath() + "spring/";
	}

	public synchronized static XmlReader newInstance() {
		if (null == instance) {
			instance = new XmlReader();
		}
		return (instance);
	}

	public List<TaskEntity> readerConfig() {
		try {
			return validate();
		} catch (Exception e) {
			try {
				return validateJar();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return new ArrayList<TaskEntity>();
	}

	private List<TaskEntity> validate() throws Exception {
		InputStream in = new FileInputStream(filePath + fileName);
		SAXBuilder sx = new SAXBuilder();
		Document doc = sx.build(in);
		return initTaskEntitys(doc);
	}

	private List<TaskEntity> validateJar() throws Exception {
		InputStream in = this.getClass().getResourceAsStream("/spring/" + fileName);
		SAXBuilder sx = new SAXBuilder();
		Document doc = sx.build(in);
		return initTaskEntitys(doc);
	}

	/**
	  * description: 初始化license信息
	  * @param info license配置串
	  * @throws Exception
	 */
	private List<TaskEntity> initTaskEntitys(Document doc) throws Exception {
		List<TaskEntity> result = new ArrayList<TaskEntity>();

		Element rootelement = doc.getRootElement();
		List<Element> childs = rootelement.getChildren();
		for (int i = 0; i < childs.size(); i++) {
			TaskEntity tModel = new TaskEntity();
			tModel.setTaskKey("task-" + getRandomStr("", 9));
			tModel.setClassName(childs.get(i).getChildText("class"));
			tModel.setMethodName(childs.get(i).getChildText("methodName"));
			tModel.setTaskType(childs.get(i).getChildText("taskType"));
			String intervalType = Validator.getDefaultStr(childs.get(i).getChildText("initialDelay"), "0");
			tModel.setIntervalType(Long.valueOf(intervalType).longValue());
			tModel.setHour(Long.valueOf(childs.get(i).getChildText("hour")));
			tModel.setMinute(Long.valueOf(childs.get(i).getChildText("minute")));
			tModel.setSecond(Long.valueOf(childs.get(i).getChildText("second")));
			if (Validator.isNotNull(childs.get(i).getChildText("startTime"))) {
				tModel.setStartTime(Integer.valueOf(childs.get(i).getChildText("startTime")));
			}
			if (Validator.isNotNull(childs.get(i).getChildText("endTime"))) {
				tModel.setEndTime(Integer.valueOf(childs.get(i).getChildText("endTime")));
			}
			if (Validator.isNotNull(childs.get(i).getChildText("taskStatus"))) {
				tModel.setTaskStatus(Integer.valueOf(childs.get(i).getChildText("taskStatus")));
			}
			tModel.setDescription(childs.get(i).getChildText("description"));
			result.add(tModel);
		}
		return result;
	}

	/**
	 * description:  写任务配置
	 * @param tasks
	 * @return   
	 * @author Hou Dayu  
	 * @update 2015-1-21
	 */
	public boolean writeXml(List<TaskEntity> tasks) {
		boolean mark = false;
		StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		sb.append("  <taskconfig>\n");
		if (!Validator.isEmpty(tasks)) {
			for (TaskEntity task : tasks) {
				sb.append("    <task>\n");
				sb.append("       <class>" + task.getClassName() + "</class>\n");
				sb.append("       <methodName>" + task.getMethodName() + "</methodName>\n");
				sb.append("       <taskType>" + task.getTaskType() + "</taskType>\n");
				sb.append("       <intervalType>" + task.getIntervalType() + "</intervalType>\n");
				sb.append("       <hour>" + task.getHour() + "</hour>\n");
				sb.append("       <minute>" + task.getMinute() + "</minute>\n");
				sb.append("       <second>" + task.getSecond() + "</second>\n");
				sb.append("       <startTime>" + task.getStartTime() + "</startTime>\n");
				sb.append("       <endTime>" + task.getEndTime() + "</endTime>\n");
				sb.append("       <description>" + task.getDescription() + "</description>\n");
				sb.append("       <taskStatus>" + task.getTaskStatus() + "</taskStatus>\n");
				sb.append("    </task>\n");
			}
		}
		sb.append("  </taskconfig>");
		mark = newCreateFile(filePath, sb.toString());
		return mark;
	}

	public String noZero(String key, int leng, String align) {
		String gest = "";
		String value = "";
		for (int i = 0; i < leng; i++) {
			gest += "0";
		}
		if ("l".equals(align)) {
			value = gest + key;
		} else {
			value += key + gest;
		}
		return value;
	}

	/**
	 * 按类型与长度生成随机数
	 *
	 * @param type   word为纯字母，number为纯数字，其他为字母与数字
	 * @param maxNum 随机数的长度
	 * @return
	 * @author Hou Dayu
	 */
	public String getRandomStr(String type, int maxNum) {
		String numStr = "";
		int count = 36;
		if ("word".equalsIgnoreCase(type)) {
			numStr = "abcdefghigkmnopqrstuvwsyzl";
			count = 26;
		} else if ("number".equalsIgnoreCase(type)) {
			numStr = "0123456789";
			count = 10;
		} else {
			numStr += "ab0cde2fgh8ig6klm9no3pqr7stu4vws5yz1";
		}
		String str = "";
		int intRd = 0; //存放随机数
		boolean[] bool = new boolean[count];
		Random rdm = new Random();
		for (int i = 0; i < maxNum; i++) {//随机排序
			do {
				intRd = rdm.nextInt(count); //假如产生的数相同继续循环
			} while (bool[intRd]);
			bool[intRd] = true;
			str += numStr.charAt(intRd);
		}
		return str;
	}

	/**
	 * 创建新的文件
	 * 
	 * @param filePathAndName 文件名称
	 * @param fileContent     文件内容
	 */
	private boolean newCreateFile(String filePathAndName, String fileContent) {
		boolean result = true;
		newCreateFolder(filePathAndName);
		try {
			FileOutputStream fo = new FileOutputStream(filePathAndName + fileName);//"content_page.js");
			OutputStreamWriter osw = new OutputStreamWriter(fo, "UTF-8");
			PrintWriter out1 = new PrintWriter(osw);
			out1.println(fileContent);
			out1.close();
			osw.close();
			fo.close();
		} catch (Exception e) {
			return false;
		}
		return result;
	}

	/**
	 * 新建目录操作
	 * 
	 * @param folderPath 文件夹路径
	 */
	private boolean newCreateFolder(String folderPath) {
		boolean result = false;
		try {
			if (Validator.isNotNull(folderPath)) {
				File newFilePath = new File(folderPath);
				if (!newFilePath.exists()) {
					result = newFilePath.mkdirs();
				}
				File newFile = new File(folderPath + fileName);
				if (!newFile.exists()) {
					return newFile.createNewFile();
				}
			}
		} catch (Exception e) {
			return false;
		}
		return result;
	}
}
